package cn.edu.scau.dormitory_management_system.module.user.controller;


import cn.edu.scau.dormitory_management_system.entity.UserEntity;
import cn.edu.scau.dormitory_management_system.exception.RRException;
import cn.edu.scau.dormitory_management_system.module.user.service.UserService;
import cn.edu.scau.dormitory_management_system.util.MapCache;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.io.IOUtils;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName BaseController
 * @Description 公共
 * @Author wlf
 * @Date 2021/5/30 15:48
 * @Version 1.0
 **/
@Controller
public class BaseController {

    protected MapCache cache = MapCache.single();

    @Autowired
    UserService userService;

    @Autowired
    private Producer producer;

    @RequestMapping(value = "activate/{code}", method = RequestMethod.GET)
    public String activate(@PathVariable("code") String code) {
        System.out.println(code);
        if (code == null || code.length() < 10) {
            return "invalid";
        }
        UserEntity user0 = userService.queryUserByRandomCode(code);
        if (user0 != null) {

            if (user0.getIsEnabled() == 0) {
                user0.setIsEnabled(1);
                if (userService.update(user0)) {
                    return "success";
                } else {
                    return "fail";
                }
            } else if (user0.getIsEnabled() == 1) {
                return "already";
            } else {
                return "invalid";
            }
        } else {  //invalid
            return "invalid";
        }
    }
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response,@RequestParam("uuid")  String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        if (StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }

        String code = producer.createText();
        //获取图片验证码
        BufferedImage image = producer.createImage(code);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
        cache.set(uuid,code,60 * 10);
    }
}
